<template>
	<div class="page-wrapper">
		<el-scrollbar height="100%">
			<div>
				<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
					<el-tab-pane label="脸彩(打火机)" name="tab1"><div class="mb20 font18 w100 textC bold">脸彩(打火机)库存剩余：{{ total1 }}</div></el-tab-pane>
					<el-tab-pane label="脸彩(小椭圆)" name="tab2"><div class="mb20 font18 w100 textC bold">脸彩(小椭圆)库存剩余：{{ total2 }}</div></el-tab-pane>
					<el-tab-pane label="子弹散装(有标)" name="tab3"><div class="mb20 font18 w100 textC bold">子弹散装(有标)库存剩余：{{ total3 }}</div></el-tab-pane>
					<el-tab-pane label="子弹散装(无标)" name="tab4"><div class="mb20 font18 w100 textC bold">子弹散装(无标)库存剩余：{{ total4 }}</div></el-tab-pane>
					<el-tab-pane label="子弹三色盒子" name="tab5"><div class="mb20 font18 w100 textC bold">子弹三色盒子库存剩余：{{ total5 }}</div></el-tab-pane>
					<el-tab-pane label="其他" name="tab6"><div class="mb20 font18 w100 textC bold">6色彩虹条（长）和假血库存剩余：{{ total6 }}</div></el-tab-pane>
				</el-tabs>
			</div>
			<div v-loading="loading">
				<div ref="mainRef" style="width: 100%; height: 700px"></div>
			</div>
		</el-scrollbar>
        <el-dialog v-model="visible" :title="title" width="1200px" center :destroy-on-close="true">
           <div class="w100">
            <div class="textR mb10">{{ totalText }}</div>
            <el-scrollbar height="600px">
                <el-table :data="itemList" border style="width: 100%" width="100%" height="100%" v-if="itemType==1">
                    <el-table-column prop="order_sn" label="入库单号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="batch_no" label="批次号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="in_time" label="入库时间" header-align="center" align="center" width="100"></el-table-column>
                    <el-table-column prop="in_type" label="入库类型" header-align="center" align="center">
                        <template #default="scope">
                            <span v-if="scope.row.in_type == 1">产品采购入库</span>
                            <span v-if="scope.row.in_type == 2">材料采购入库</span>
                            <span v-if="scope.row.in_type == 3">退货入库</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="入库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="supplier_name" label="供应商名称" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="operator" label="操作人" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="created_at" label="操作时间" header-align="center" align="center" width="100"></el-table-column>
                </el-table>
                <el-table :data="itemList" border style="width: 100%" width="100%" height="100%" v-if="itemType==2">
                    <el-table-column prop="order_sn" label="出库单号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="out_time" label="出库时间" header-align="center" align="center" width="100"></el-table-column>
                    <el-table-column prop="out_type" label="出库类型" header-align="center" align="center">
                        <template #default="scope">
                            <span v-if="scope.row.out_type == 1">生产出库</span>
                            <span v-if="scope.row.out_type == 2">销售出库</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="出库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="customer_name" label="客户名称" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="remark" label="出库备注" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="operator" label="操作人" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="created_at" label="操作时间" header-align="center" align="center" width="100"></el-table-column>
                </el-table>
            </el-scrollbar>
           </div>
        </el-dialog>
	</div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, onBeforeUnmount } from 'vue'
import { getInventoryItem, getProduct } from '@/api/api'
import { ElMessage } from 'element-plus'
import { Sort } from '@element-plus/icons-vue'
import { hasRule } from '@/utils/tool'
import * as echarts from 'echarts'

const totalText = ref('');
const total1 = ref(0);
const total2 = ref(0);
const total3 = ref(0);
const total4 = ref(0);
const total5 = ref(0);
const total6 = ref(0);
const title = ref('');
const itemType = ref(1);
const visible = ref(false);
const itemList = ref([]);
const currentMenu = ref()
const activeName = ref('tab1')
const loading = ref(true)
const handleClick = (tab, event) => {
    if (currentMenu.value && currentMenu.value.parentNode === document.body) {
        document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
    }
	if (myChart.value) {
		myChart.value.clear()
	}
	if (tab.paneName == 'tab1') {
		init('脸彩(打火机)',5)
	} else if (tab.paneName == 'tab2') {
		init('脸彩(小椭圆)',11)
	} else if (tab.paneName == 'tab3') {
		init('子弹散装(有标)',6)
	} else if (tab.paneName == 'tab4') {
		init('子弹散装(无标)',12)
	} else if (tab.paneName == 'tab5') {
		init('子弹三色盒子',7, 8)
	} else if (tab.paneName == 'tab6') {
		init('其他',4, 9)
	}
}
onBeforeUnmount(() => {
    if (currentMenu.value && currentMenu.value.parentNode === document.body) {
        document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
    }
})
onMounted(() => {
	init('脸彩(打火机)',5)
})
const getFontColor = text => {
	const colorList = [
		{ font: '红', color: '#C23019' },
		{ font: '白', color: '#EDEDED' },
		{ font: '蓝', color: '#2C3D95' },
		{ font: '黑', color: '#303030' },
		{ font: '黄', color: '#EDCA50' },
		{ font: '绿', color: '#127A00' },
		{ font: '咖', color: '#4C1B01' },
		{ font: '浅蓝', color: '#79A2D3' },
		{ font: '橙', color: '#D86E13' },
		{ font: '紫', color: '#983593' }
	]
	const item = colorList.find(i => i.font == text)
	if (item) {
		return item.color
	} else {
		return '#303030'
	}
}
const mainRef = ref()
const myChart = ref(null)
const init = async (name, one, two) => {
    let rotate = 0;
    total1.value = 0;
    total2.value = 0;
    total3.value = 0;
    total4.value = 0;
    total5.value = 0;
    total6.value = 0;
	loading.value = true
	if (myChart.value === null) {
		myChart.value = echarts.init(mainRef.value)
	}
	let data1 = await getProduct(one)
	let data2 = null
	let sku1 = null
	let sku2 = null
	if (two) {
		data2 = await getProduct(two)
	}
	sku1 = data1.data.sku
	if (data2) {
		console.log(data2.data.sku)
		sku2 = data2.data.sku
	}
	// console.log('sku1', sku1)
	// console.log('sku2', sku2)
	let xData = []
	let seriesData = [
		{
			label: {
				show: true,
				position: 'top', // 顶部显示
				formatter: params => {
					return `${params.name=='红白'?Number(params.value * 2).toFixed(0):Number(params.value * 3).toFixed(0)} `
				} // 显示数据值
			},
			data: [],
			type: 'bar',
            barMaxWidth: '150',
			stack: 'stack1' // 使用相同的堆叠名，以便在同一根柱子上绘制
		},
		{
			data: [],
			type: 'bar',
            barMaxWidth: '150',
			stack: 'stack1' // 堆叠，使得可以绘制多段颜色
		},
		{
			data: [],
			type: 'bar',
            barMaxWidth: '150',
			stack: 'stack1' // 使用相同的堆叠名，以便在同一根柱子上绘制
		}
	]
	if (one == 7) {
		xData = [sku1[0].name, sku2[0].name]
		seriesData[0].data.push({ diyname: name, diyid:sku1[0].id, value: sku1[0].inventory / 3, itemStyle: { color: getFontColor('黑') }, emphasis: { disabled: true } })
		seriesData[1].data.push({ diyname: name, diyid:sku1[0].id, value: sku1[0].inventory / 3, itemStyle: { color: getFontColor('绿') }, emphasis: { disabled: true } })
		seriesData[2].data.push({ diyname: name, diyid:sku1[0].id, value: sku1[0].inventory / 3, itemStyle: { color: getFontColor('咖') }, emphasis: { disabled: true } })
		seriesData[0].data.push({ diyname: name, diyid:sku2[0].id, value: sku2[0].inventory / 3, itemStyle: { color: getFontColor('黑') }, emphasis: { disabled: true } })
		seriesData[1].data.push({ diyname: name, diyid:sku2[0].id, value: sku2[0].inventory / 3, itemStyle: { color: getFontColor('绿') }, emphasis: { disabled: true } })
		seriesData[2].data.push({ diyname: name, diyid:sku2[0].id, value: sku2[0].inventory / 3, itemStyle: { color: getFontColor('咖') }, emphasis: { disabled: true } })
        total5.value = sku1[0].inventory+sku2[0].inventory;
	} else if (one == 4) {
		xData = [...sku1.map(i => i.name + i.attr.two_name), sku2[0].name]
		seriesData = [
			{
				label: {
					show: true,
					position: 'top', // 顶部显示
					formatter: params => {
						return `${Number(params.value).toFixed(0)} `
					} // 显示数据值
				},
				data: [],
                barMaxWidth: '150',
				type: 'bar'
			}
		]
		// seriesData[0].data.push({ diyname: name, diyid:sku1[0].id, value: sku1[0].inventory, itemStyle: { color: getFontColor('白') }, emphasis: { disabled: true } })
        sku1.forEach(item => {
            seriesData[0].data.push({ diyname: name, diyid:item.id, value: item.inventory, itemStyle: { color: getFontColor('白') }, emphasis: { disabled: true } })
        })
		seriesData[0].data.push({ diyname: name, diyid:sku2[0].id, value: sku2[0].inventory, itemStyle: { color: getFontColor('红') }, emphasis: { disabled: true } })
        total6.value = sku1[0].inventory+sku2[0].inventory;
	} else if (one == 6 || one == 12) {
		seriesData = [
			{
				label: {
					show: true,
					position: 'top', // 顶部显示
					formatter: params => {
						return `${Number(params.value).toFixed(0)} `
					} // 显示数据值
				},
				data: [],
                barMaxWidth: '150',
				type: 'bar'
			}
		]
		sku1.forEach(item => {
			xData.push(item.attr_name);
			seriesData[0].data.push({ diyname: name, diyid:item.id, value: item.inventory, itemStyle: { color: getFontColor(item.attr_name.slice(0, 1)) }, emphasis: { disabled: true } });
            total3.value += item.inventory;
            total4.value += item.inventory;
		})
	} else {
		sku1.forEach(item => {
            total1.value += item.inventory;
            total2.value += item.inventory;
			xData.push(item.attr_name)
			const nameList = item.attr_name.split('')
			if (nameList.length == 3) {
				nameList.forEach((jtem, j) => {
					seriesData[j].data.push({ diyname: name, diyid:item.id, value: item.inventory / 3, itemStyle: { color: getFontColor(jtem) }, emphasis: { disabled: true } })
				})
			} else if (item.attr_name == '红白') {
				seriesData[0].data.push({ diyname: name, diyid:item.id, value: item.inventory / 2, itemStyle: { color: getFontColor('红') }, emphasis: { disabled: true } })
				seriesData[1].data.push({ diyname: name, diyid:item.id, value: item.inventory / 2, itemStyle: { color: getFontColor('白') }, emphasis: { disabled: true } })
				seriesData[2].data.push({ diyname: name, diyid:item.id, value: 0, itemStyle: { color: getFontColor() }, emphasis: { disabled: true } })
			} else if (item.attr_name == '6色') {
				seriesData[0].data.push({ diyname: name, diyid:item.id, value: item.inventory / 3, itemStyle: { color: getFontColor('白') }, emphasis: { disabled: true } })
				seriesData[1].data.push({ diyname: name, diyid:item.id, value: item.inventory / 3, itemStyle: { color: getFontColor('白') }, emphasis: { disabled: true } })
				seriesData[2].data.push({ diyname: name, diyid:item.id, value: item.inventory / 3, itemStyle: { color: getFontColor('白') }, emphasis: { disabled: true } })
			} else {
				seriesData[0].data.push({ diyname: name, diyid:item.id, value: item.inventory / 3, itemStyle: { color: getFontColor('白') }, emphasis: { disabled: true } })
				seriesData[1].data.push({ diyname: name, diyid:item.id, value: item.inventory / 3, itemStyle: { color: getFontColor('白') }, emphasis: { disabled: true } })
				seriesData[2].data.push({ diyname: name, diyid:item.id, value: item.inventory / 3, itemStyle: { color: getFontColor('白') }, emphasis: { disabled: true } })
			}
		})
        if(sku1.length > 10) {
            rotate = 30
        }
        if(sku1.length > 30) {
            rotate = 40
        }
        if(sku1.length > 40) {
            rotate = 50
        }
        if(sku1.length > 50) {
            rotate = 60
        }
	}
	// console.log(seriesData)
	let option = {
		animation: false,
		xAxis: {
			type: 'category',
			data: xData,
            axisLabel: {
                show: true,
                rotate: rotate,//35度角倾斜显示
            }
		},
		yAxis: {
			type: 'value'
		},
		series: seriesData.reverse()
		// series: [
		// 	{
		// 		data: [
		// 			{ value: 50, itemStyle: { color: '#2C3D95' }, emphasis: { disabled: true } }, // 第三部分数据，蓝
		// 			{ value: 50, itemStyle: { color: '#EDCA50' }, emphasis: { disabled: true } } // 第三部分数据，黄
		// 		],
		// 		type: 'bar',
		// 		stack: 'stack1' // 堆叠，使得可以绘制多段颜色
		// 	},
		// 	{
		// 		data: [
		// 			{ value: 50, itemStyle: { color: '#EDEDED' }, emphasis: { disabled: true } }, // 第二部分数据，白
		// 			{ value: 50, itemStyle: { color: '#C23019' }, emphasis: { disabled: true } } // 第二部分数据，红
		// 		],
		// 		type: 'bar',
		// 		stack: 'stack1' // 使用相同的堆叠名，以便在同一根柱子上绘制
		// 	},
		// 	{
		// 		label: {
		// 			show: true,
		// 			position: 'top', // 顶部显示
		// 			formatter: params => {
		// 				return `${150} `
		// 			} // 显示数据值
		// 		},
		// 		data: [
		// 			{ value: 50, itemStyle: { color: '#C23019' }, emphasis: { disabled: true } }, // 第一部分数据，红
		// 			{ value: 50, itemStyle: { color: '#303030' }, emphasis: { disabled: true } } // 第一部分数据，黑
		// 		],
		// 		type: 'bar',
		// 		stack: 'stack1' // 使用相同的堆叠名，以便在同一根柱子上绘制
		// 	}
		// ]
	}
	// 绘制图表
	myChart.value.setOption(option)
    chartLeftEvent(myChart.value);
    chartRightEvent(myChart.value);
	loading.value = false
}
const chartRightEvent = (chart) => {
    chart.getZr().on('contextmenu', params => {
		params.event.preventDefault() // 取消默认右击事件
		// 使用箭头函数
		if (currentMenu.value && currentMenu.value.parentNode === document.body) {
			document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
		}
	})
}
const chartLeftEvent = (chart) => {
    chart.on('click', params => {
		// console.log('params', params)
        if(!hasRule('admin/inventory/inventory')){
            return;
        }
		if (currentMenu.value && currentMenu.value.parentNode === document.body) {
			document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
		}

		const menu = document.createElement('div')
		menu.classList.add('custom-menu') // 添加自定义样式类名
		menu.style.cssText = `
            left: ${params.event.event.pageX}px;
            top: ${params.event.event.pageY}px;
        `
		document.body.appendChild(menu)

		const menuItem1 = document.createElement('div')
		menuItem1.className = 'menu-item'
		menuItem1.style.cssText = `
          border-radius: 0px 10px 0px 0px;
        `
		menuItem1.innerText = '查看入库记录'
		menuItem1.onclick = () => {
			// console.log('查看入库记录')
            handleCheck(params,1);
			if (currentMenu.value && currentMenu.value.parentNode === document.body) {
				document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
			}
		}
		menu.appendChild(menuItem1)

		const menuItem2 = document.createElement('div')
		menuItem2.className = 'menu-item'
		menuItem2.style.cssText = `
          border-radius: 0px 0px 0px 10px;
        `
		menuItem2.innerText = '查看出库记录'
		menuItem2.onclick = () => {
			// console.log('查看出库记录')
            handleCheck(params,2);
			if (currentMenu.value && currentMenu.value.parentNode === document.body) {
				document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
			}
		}
		menu.appendChild(menuItem2)

		currentMenu.value = menu // 保存当前菜单元素
	})
}
const handleCheck = (row, type) => {
    itemType.value = type;
    if(type==1){
        title.value = `${row.data.diyname}（${row.name}）入库记录`;
    }else{
        title.value = `${row.data.diyname}（${row.name}）出库记录`;
    }
    itemList.value = [];
    visible.value = true;
    totalText.value = '';
    getInventoryItem({
        product_id: row.data.diyid,
        type: type,
    }).then((result) => {
        itemList.value = result.data;
        const tal = result.data.reduce((total, item) => {
            return total + item.quantity;
        }, 0)
        if(type==1){
            totalText.value = `入库总数量：${Math.floor(tal)}`;
        }else{
            totalText.value = `出库总数量：${Math.floor(tal)}`;
        }
    }).catch((err) => {
        
    });
}
</script>
<style>
/* echarts图表样式 */
.custom-menu {
	position: absolute;
	width: 130px;
	box-shadow: rgb(0 0 0 / 30%) 1px 1px 3px;
	z-index: 999;
	background: rgb(69 140 199 / 80%);
	border: none;
	border-radius: 0px 10px 0px 10px;
	color: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.menu-item {
	padding: 5px 0px;
	cursor: pointer;
	width: 100%;
	display: flex;
	justify-content: center;
}

.menu-itemborder1 {
	border-radius: 0px 10px 0px 0px;
}

.menu-itemborder2 {
	border-radius: 0px 0px 0px 10px;
}

.menu-item:hover {
	background-color: #a2bbda;
}
</style>
